import cv2
import numpy as np

# 1. 图片输入
image_np = cv2.imread('duilian.jpg')
# 获取高度和宽度
h = image_np.shape[0]
w = image_np.shape[1]
print(h, w)

# 2. 图片切割
#x_min, x_max = 470, 830
#y_min, y_max = 150, 280
#x_min, x_max = 40, 170
#y_min, y_max = 380, 1150
x_min, x_max = 1100, 1255
y_min, y_max = 380, 1150

try:
    if not (x_min >= 0 and y_min >= 0 and x_max < w and y_max < h and x_max > x_min and y_max > y_min):
        raise ValueError('ROI区域设定有误！！！')
    # 切片（左闭右开）
    ROI_image = image_np.copy()[y_min:y_max, x_min:x_max]
    # 把要切出的区域花个框
    line_width = 4  # 框的宽度
    # 画出范围
    cv2.rectangle(
        image_np,
        (x_min, y_min),
        (x_max, y_max),
        (0, 0, 255),
        line_width
    )
except Exception as e:
    # 如果出错，弹出错误信息
    print('程序运行出错：', e)

# 3. 图片输出
cv2.imwrite('ROI_image_up.jpg', ROI_image)
cv2.imshow('image_np', image_np)
cv2.waitKey(0)
